/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.starmeep.classes;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author marc
 */
public class StarSSH {
    public static final String USER_ROOT="root";

    private Session sshsession=null;

    public StarSSH(String pemfile, String knowhost, String user, String host) throws JSchException {
        JSch jsch=new JSch();
        jsch.addIdentity(pemfile);
//   jsch.addIdentity(pubkeyfile, passphrase);
        jsch.setKnownHosts(knowhost);

        sshsession=jsch.getSession(user, host, 22);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        sshsession.setConfig(config);
        sshsession.connect();

    }

    public String executeCommand(String command) throws IOException, JSchException{
        String message="";

        Channel channel=sshsession.openChannel("exec");
        ChannelExec chexe= (ChannelExec) channel;
        chexe.setCommand(command);

        channel.setInputStream(null);
        chexe.setErrStream(System.err);
        InputStream in=channel.getInputStream();

        channel.connect();

        byte[] tmp=new byte[1024];
        while(true){
            while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;
                //System.out.print(new String(tmp, 0, i));
                message+=(new String(tmp, 0, i));
                message+="\n";
            }
            if(channel.isClosed()){
                //System.out.println("exit-status: "+channel.getExitStatus());
                message+=("exit-status: "+channel.getExitStatus());
                message+="\n";
                break;
            }
            try{Thread.sleep(1000);}catch(Exception ee){}
        }
        channel.disconnect();
        return message;
    }

    public void sftpFile(File localFile, String filename, String remoteDirectory) throws Exception {
        ChannelSftp channel = (ChannelSftp)sshsession.openChannel("sftp");
        channel.connect();
        channel.cd(remoteDirectory);
        channel.put(new FileInputStream(localFile), filename);
        channel.disconnect();
    }

    public void closeConnection(){
        sshsession.disconnect();
    }

}